<template>
    <van-search
        v-model="keyword"
        placeholder="输入关键字搜索(8字以内)"
        maxlength="8"
        show-action
        @search="onSearch"
    ></van-search>
    <van-loading type="spinner" v-show="state.loading"></van-loading>
    <van-list
        v-show="state.ready && state.list.length"
        :finished="state.finished"
        finish-text="人家是有底线的"
    >
        <news-item
            v-for="(item, index) in state.list"
            :key="index"
            :data="item"
            @click="newsDetail(index)"
        ></news-item>
    </van-list>
    <van-empty
        v-show="state.ready && !state.list.length"
        image="search"
        description="暂无相关搜索结果"
    ></van-empty>
</template>

<script>
import { defineComponent, reactive, ref } from '@vue/runtime-core'
import { searchNews } from '@/utils/request'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default defineComponent({
    setup() {
        const keyword = ref('')
        const onSearch = async (keyword) => {
            state.ready = false
			state.loading = true

            if (!keyword.length) return false
            let { data } = await searchNews({ keyword })
            state.list = data.list ? data.list.filter(item=>item.content) : []
            state.ready = true
			state.loading = false
        }

        const state = reactive({
            list: [],
            ready: false,
            finished: true,
			loading: false
        })

        const router = useRouter()
		const store  = useStore()
        const newsDetail = (index) => {
			store.commit('updateSearchResult', { list: state.list })
			router.push(`/detail/search/${index}`)
        }

        return {
            state,
            keyword,
            onSearch,
            newsDetail,
        }
    },
})
</script>

<style scoped>
.van-loading {
    text-align: center;
    color: #1a82fc;
    line-height: 60px;
}
</style>
